#include "Frame.h"
#define TFILE <J3Control/main.t>
#include <Core/t.h>

#define IMAGECLASS FrameImg
#define IMAGEFILE <J3Control/Frame.iml>
#include <Draw/iml.h>

//外部的inject方法
void orj(String loadername, String dllname, int pid, String& output)
{
	if(!FileExists(loadername))
	{
		PromptOK(loadername + t_("not found"));
		return;
	}
	if(!FileExists(loadername))
	{
		PromptOK(dllname + t_("not found"));
		return;
	}
	
     String dllFpath = ToSystemCharset(GetDataFile(dllname));
     String commandline = Format("%s %d %s", loadername,  pid, dllFpath);
    
     LocalProcess lp(commandline); Cout() << commandline << "\n";
     while(lp.IsRunning())
     {
          String tmp;
          lp.Read(tmp);
          Cout() << tmp;
          output += tmp;
     }
}

Frame::Frame()
{
	CtrlLayout(*this, t_("Window title"));
	Sizeable().Icon(FrameImg::share());
	tab.Add(pg.SizePos(), t_("page"));	
	WhenClose = THISBACK(Exit);
	
	//状态栏
	AddFrame(status);
	//菜单
	AddFrame(menu);
	menu.Set(THISBACK(MainMenu));
	//回调函数赋值
	pg.cb_Inj = callback(this, &Frame::oij);
	pg.cb_Send = callback(this, &Frame::sendm);
}

void Frame::Exit()
{
	if(PromptOKCancel(t_("Exit?")))
	{
		Close();	
	}
}

void Frame::OnSetting()
{
	WithSettingLayout<TopWindow> dlg;
	CtrlLayoutOKCancel(dlg, t_("Setting"));
	dlg.e_class = className;
	
	if(dlg.Execute() == IDOK)
	{
		className = ~dlg.e_class;
	}
}

void Frame::SubMenu(Bar& bar)
{		
	bar.Add(t_("Setting"), THISBACK(OnSetting));
}


void Frame::MainMenu(Bar& bar) {
	bar.Add(t_("Menu"), THISBACK(SubMenu));
}

void Frame::PrintLog(String str, Color r)
{
	Time time = GetSysTime();
	String log = Format("%d/%d/%d %d:%d:%d %s\n", time.year, time.month, time.day, time.hour, time.minute, time.second, str);
	
	int n = doc.GetLength();
	doc.Insert(n, log);
}

void Frame::PrintMsg(String msg)
{
	status = msg;
}

void Frame::oij()
{
	DWORD pid = 0;
	HWND hwnd = FindWindow(className,NULL);
	if(hwnd == NULL)
	{
		PrintLog(t_("no hwnd"));
		return;
	}
	GetWindowThreadProcessId(hwnd, &pid);
	if(pid == NULL)
	{
		PrintLog(t_("no pid"));
		return;
	}
	
	//更新最新的窗口句柄
	curHwnd = hwnd;
	PrintMsg(AsString(curHwnd) + " PID: " + AsString(pid));
	
	String log;
	orj("RemoteDLLInjector32.exe","msgbox.dll",pid,log);
	PrintLog(log);
}

void Frame::sendm(int n)
{
	::SendMessage(curHwnd, n, NULL, NULL);
	PrintLog(String("SendMessage:") + AsString(n));
}


GUI_APP_MAIN
{
	SetLanguage(LNGC_('Z','H','C','N', CHARSET_UNICODE));
	static const char unique_name[] = "FrameCheck_$_$_U++";
	if(::FindWindow(NULL, unique_name)) {
		Exclamation(t_("J3ControlCheck is already running."));
		return;
	}
	TopWindow singlechk;
	singlechk.SetRect(-1, -1, 1, 1);
	singlechk.Hide();
	singlechk.Title(unique_name);
	singlechk.Open();
	
	Frame hb;	
	LoadFromFile(hb);	
	hb.Run();
	StoreToFile(hb);
}
